<template>
  <base-container>
    <base-table-card class="mb78px!">
      <el-form ref="formRef" :model="form" :rules="formRules" class="content-form" label-width="100px">
        <!-- 同宽容器 -->
        <div class="max-w-[560px] w-full">
          <!-- 服务类目（编辑态禁用） -->
          <el-form-item label="服务类目" prop="categoryId" class="w-full">
            <el-select
              v-model="form.categoryId"
              :disabled="loadingCats || isEdit"
              filterable
              clearable
              placeholder="请选择服务类目"
              class="w-full"
            >
              <el-option
                v-for="opt in catOptions"
                :key="opt.categoryId"
                :label="opt.categoryName"
                :value="String(opt.categoryId)"
              />
            </el-select>

            <template v-if="!loadingCats && catOptions.length === 0 && !isEdit">
              <span class="ml-3 text-[var(--el-text-color-secondary)]">
                你还未设置内容类目，无法选择。
                <el-link type="primary" :underline="false" @click="handleGotoCategory"> 去设置类目 &gt; </el-link>
              </span>
            </template>
          </el-form-item>

          <!-- 内容标题（编辑态可改） -->
          <el-form-item label="内容标题" prop="title" class="w-full">
            <el-input
              v-model.trim="form.title"
              maxlength="100"
              show-word-limit
              placeholder="请输入，限制100字"
              clearable
              class="w-full"
            />
          </el-form-item>
        </div>

        <!-- 富文本（编辑态可改） -->
        <el-form-item label="内容详情" prop="contentHtml">
          <div class="relative w-full max-w-[1200px] overflow-hidden rounded-[8px] border border-[var(--cb1)]">
            <div v-if="uploading" class="absolute inset-0 z-10 flex items-center justify-center bg-white/60">
              <el-progress :percentage="progress" type="circle" :width="96" :color="progressColor" />
            </div>

            <Toolbar :editor="editorRef" :default-config="toolbarCfg" mode="default" />
            <Editor
              v-model="form.contentHtml"
              :default-config="editorCfg"
              :style="{ height: editorHeight }"
              mode="default"
              @on-created="handleEditorCreated"
              @on-change="handleEditorChange"
            />
          </div>
        </el-form-item>

        <!-- 发送时间（编辑态禁用） -->
        <el-form-item label="发送时间" prop="sendMode">
          <el-radio-group v-model="form.sendMode" :disabled="isEdit">
            <el-radio :label="'NOW'">立即发送</el-radio>
            <el-radio :label="'MANUAL'">手动发送</el-radio>
            <el-radio :label="'SCHEDULE'">定时发送</el-radio>
          </el-radio-group>
          <el-date-picker
            v-if="form.sendMode === 'SCHEDULE'"
            v-model="form.scheduleTime"
            class="ml-2"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择发送时间"
            :disabled="isEdit"
            :disabled-date="isDateDisabled"
            @change="handleScheduleChange"
          />
        </el-form-item>

        <!-- 触达对象（来自字典；按类目过滤；编辑态禁用） -->
        <el-form-item label="触达对象" prop="targets">
          <el-checkbox-group v-model="form.targets" :disabled="isEdit">
            <el-checkbox v-for="opt in targetOptions" :key="opt.value" :label="opt.value">
              {{ opt.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 商家筛选（仅当包含"商家"code 才展示；编辑态禁用） -->
        <el-form-item v-if="form.targets.includes(merchantCode)">
          <div class="merchant-card">
            <el-form-item label="商家等级" prop="merchantGrade" class="mb-2">
              <el-checkbox-group v-model="form.merchantGrade" :disabled="isEdit">
                <el-checkbox v-for="opt in merchantGradeOptions" :key="opt.value" :label="opt.value">
                  {{ opt.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="商家类型" prop="merchantType">
              <el-checkbox-group v-model="form.merchantType" :disabled="isEdit">
                <el-checkbox v-for="opt in merchantTypeOptions" :key="opt.value" :label="opt.value">
                  {{ opt.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>
        </el-form-item>
        <!-- ======================= 是否滚动 ======================= -->
        <!-- 自定义标签：文字 + 提示图标 -->
        <!-- <el-form-item prop="isScroll">
          <template #label>
            <span class="fi-label">
              是否滚动
              <el-tooltip
                effect="dark"
                placement="top"
                :raw-content="true"
                content="如公告内容非常重要，可设置滚动显示。<br/>设置后该公告将在 Web 顶部或首页滚动公告中显示。"
              >
                <base-icon name="iconfont-general gen-guanyushuoming" :size="16" class="fi-icon" />
              </el-tooltip>
            </span>
          </template>

          <div class="flex items-center gap-3">
            <el-radio-group v-model="form.isScroll" :disabled="isEdit">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </div>
        </el-form-item> -->

        <!-- 滚动时间（仅在“是否滚动=是”时出现） -->
        <!-- <el-form-item v-if="form.isScroll === 1" prop="scrollHours">
          <div class="scroll-box">
            <span class="scroll-label">滚动时间</span>
            <el-input
              v-model.trim="form.scrollHours"
              class="scroll-input"
              maxlength="5"
              placeholder="请输入"
              :disabled="isEdit"
              @input="onScrollHoursInput"
            />
            <span class="scroll-unit">小时</span>
          </div>
        </el-form-item> -->

        <!-- ======================= 是否弹出 ======================= -->

        <!-- <el-form-item prop="isPopup">
          <template #label>
            <span class="fi-label">
              是否弹出
              <el-tooltip
                effect="dark"
                placement="top"
                :raw-content="true"
                content="如公告内容非常重要，可以设置弹出显示，<br/>设置后该条公告将在用户登录后强制弹出一次，租户端在首页弹出。"
              >
                <base-icon name="iconfont-general gen-guanyushuoming" :size="16" class="fi-icon" />
              </el-tooltip>
            </span>
          </template>

          <div class="flex items-center gap-3">
            <el-radio-group v-model="form.isPopup" :disabled="isEdit">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </div>
        </el-form-item> -->
      </el-form>
    </base-table-card>

    <!-- 底部按钮 -->
    <div class="footer">
      <el-button class="w-50" size="large" type="primary" :loading="submitting" @click="handleSubmit">
        {{ isEdit ? "保存修改" : "确认新增" }}
      </el-button>
    </div>
  </base-container>
</template>

<script setup>
  import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
  import useWangUpload from "@/utils/useWangUpload";
  import { SEND_MAP_API } from "@/utils/const.js";

  const route = useRoute();
  const router = useRouter();
  const id = computed(() => String(route.query.id || route.params.id || ""));
  const isEdit = computed(() => !!id.value);

  /* ---------------- 常量 / 映射 ---------------- */
  const progressColor = ref("var(--bd)");
  // 滚动时间最大上限（小时）——可按需调整
  const SCROLL_HOURS_MAX = 720;

  /* ---------------- 表单 / 校验 ---------------- */
  const formRef = ref();
  const submitting = ref(false);
  const form = reactive({
    categoryId: "", // 服务类目ID
    title: "",
    contentHtml: "",
    sendMode: "NOW",
    scheduleTime: "",
    targets: [],

    // 新增：是否滚动 / 滚动时间 / 是否弹出
    isScroll: 0, // 0-否 1-是
    scrollHours: "", // 仅 isScroll=1 时必填（小时，正整数）
    isPopup: 0, // 0-否 1-是

    merchantGrade: [],
    merchantType: [],
  });

  // 自定义校验：滚动时间
  function validateScrollHours(_rule, v, cb) {
    if (form.isScroll !== 1) return cb(); // 未开启滚动则不校验
    if (!v) return cb(new Error("请输入滚动时间"));
    if (!/^[1-9]\d*$/.test(String(v))) return cb(new Error("请输入正确的滚动时间（正整数）"));
    if (Number(v) > SCROLL_HOURS_MAX) return cb(new Error(`滚动时间不能超过 ${SCROLL_HOURS_MAX} 小时`));
    cb();
  }
  function hasMeaningfulContent(html) {
    if (!html) return false;
    const div = document.createElement("div");
    div.innerHTML = html;

    // 文字内容
    const text = (div.textContent || "")
      .replace(/[\u00A0\u200B]/g, "") // nbsp/零宽
      .trim();
    if (text.length > 0) return true;

    // 媒体或结构性内容也算有效
    return !!div.querySelector(
      "img,video,audio,iframe,embed,object,canvas,svg,table tr,ul li,ol li,blockquote,pre,code"
    );
  }
  const createRules = {
    categoryId: [{ required: true, message: "请选择服务类目", trigger: "change" }],
    title: [{ required: true, message: "请输入内容标题", trigger: "blur" }],
    contentHtml: [
      { required: true, message: "请输入内容详情", trigger: ["change", "blur"] },
      {
        validator: (_r, v, cb) => (hasMeaningfulContent(v) ? cb() : cb(new Error("请输入内容详情"))),
        trigger: ["change", "blur"],
      },
    ],
    sendMode: [{ required: true, message: "请选择发送时间", trigger: "change" }],
    targets: [{ required: true, type: "array", message: "请选择触达对象", trigger: "change" }],

    // 商家等级和类型校验：仅当选了"商家"触达对象时才校验
    merchantGrade: [
      {
        validator: (_r, v, cb) => {
          const hasMerchant = form.targets.includes(String(merchantCode.value));
          if (hasMerchant && (!v || v.length === 0)) {
            return cb(new Error("请选择商家等级"));
          }
          cb();
        },
        trigger: "change",
      },
    ],
    merchantType: [
      {
        validator: (_r, v, cb) => {
          const hasMerchant = form.targets.includes(String(merchantCode.value));
          if (hasMerchant && (!v || v.length === 0)) {
            return cb(new Error("请选择商家类型"));
          }
          cb();
        },
        trigger: "change",
      },
    ],

    // 新增：是否滚动 / 滚动时间 / 是否弹出
    isScroll: [{ required: true, message: "请选择是否滚动", trigger: "change" }],
    scrollHours: [{ validator: validateScrollHours, trigger: "blur" }],
    isPopup: [{ required: true, message: "请选择是否弹出", trigger: "change" }],
  };

  const editRules = {
    title: createRules.title,
    contentHtml: createRules.contentHtml,
    // 编辑场景通常不允许改滚动/弹出，如需允许可把以下三条加上
    // isScroll: createRules.isScroll,
    // scrollHours: createRules.scrollHours,
    // isPopup: createRules.isPopup,
  };

  const formRules = computed(() => (isEdit.value ? editRules : createRules));

  /* ---------------- 类目树 ---------------- */
  const loadingCats = ref(true);
  const catOptions = ref([]);

  const loadCategoryTree = async () => {
    loadingCats.value = true;
    try {
      const res = await Api.message.GetCategoryOptions({});
      const payload = res?.data ?? res;
      // 返回结构：[{ categoryId, categoryName, targetType }]
      // targetType 格式："OPE,TENANT,SHOP,CHANNEL"
      catOptions.value = Array.isArray(payload) ? payload : [];
    } catch (e) {
      console.error("加载服务类目失败:", e);
      catOptions.value = [];
    } finally {
      loadingCats.value = false;
    }
  };

  /* ---------------- 触达对象（字典 + 类目过滤） ---------------- */
  const dictAllTargets = ref([]); // [{label,value}]
  const targetOptions = ref([]);

  const merchantCode = computed(() => {
    const hit = dictAllTargets.value.find(o => /商家/.test(String(o.label || "")));
    return hit ? String(hit.value) : "OPE";
  });

  const loadApplicableDict = async () => {
    try {
      const res = await Api.dict.GetListChildrenByDictCode({
        dictCode: "qingyun.support.message.target",
      });
      const list = Array.isArray(res?.data) ? res.data : Array.isArray(res) ? res : [];
      dictAllTargets.value = list.map(i => ({ label: i.dictLabel, value: String(i.dictValue) }));
      targetOptions.value = dictAllTargets.value.slice();
    } catch (e) {
      console.error("加载触达对象字典失败：", e);
      dictAllTargets.value = [];
      targetOptions.value = [];
    }
  };

  /** 根据选中类目过滤触达对象选项，并校正已选值 */
  const handleRefreshTargetsByCategory = () => {
    if (!form.categoryId) {
      targetOptions.value = dictAllTargets.value.slice();
      return;
    }

    // 根据 categoryId 查找对应的类目
    const selectedCategory = catOptions.value.find(cat => String(cat.categoryId) === String(form.categoryId));
    let allowCodes = [];

    if (selectedCategory && selectedCategory.targetType) {
      // 使用 targetType 来过滤触达对象
      allowCodes = String(selectedCategory.targetType)
        .split(",")
        .map(s => s.trim())
        .filter(Boolean);
    } else {
      // 如果没有 targetType，显示所有触达对象
      targetOptions.value = dictAllTargets.value.slice();
      return;
    }

    const allowSet = new Set(allowCodes);
    targetOptions.value = dictAllTargets.value.filter(o => allowSet.has(String(o.value)));
    form.targets = (form.targets || []).filter(c => allowSet.has(String(c)));

    if (!allowSet.has(String(merchantCode.value))) {
      form.merchantGrade = [];
      form.merchantType = [];
    }
  };

  /* ---------------- 商家等级 / 类型（字典） ---------------- */
  const merchantGradeOptions = ref([]); // [{label,value}]
  const merchantTypeOptions = ref([]); // [{label,value}]

  const loadMerchantDicts = async () => {
    try {
      const resLevel = await Api.dict.GetListChildrenByDictCode({
        dictCode: "qingyun.support.customer.merchant.level",
      });
      const listLevel = Array.isArray(resLevel?.data) ? resLevel.data : Array.isArray(resLevel) ? resLevel : [];
      merchantGradeOptions.value = listLevel.map(i => ({
        label: i.dictLabel,
        value: String(i.dictValue),
      }));

      const resType = await Api.dict.GetListChildrenByDictCode({
        dictCode: "qingyun.support.customer.merchant.type",
      });
      const listType = Array.isArray(resType?.data) ? resType.data : Array.isArray(resType) ? resType : [];
      merchantTypeOptions.value = listType.map(i => ({
        label: i.dictLabel,
        value: String(i.dictValue),
      }));
    } catch (e) {
      console.error("加载商家等级/类型字典失败：", e);
      merchantGradeOptions.value = [];
      merchantTypeOptions.value = [];
    }
  };

  /** 选中"商家"时默认勾选等级/类型；取消时清空 */
  watch(
    () => form.targets.slice().sort().join(","),
    (newTargets, oldTargets) => {
      const oldTargetsStr = oldTargets || "";
      const newTargetsStr = newTargets || "";

      const hadMerchant = oldTargetsStr.split(",").includes(String(merchantCode.value));
      const hasMerchant = newTargetsStr.split(",").includes(String(merchantCode.value));

      if (hasMerchant && !hadMerchant) {
        // 只有从"未选择商家"变为"选择商家"时才默认全选
        if (form.merchantGrade.length === 0 && merchantGradeOptions.value.length) {
          form.merchantGrade = merchantGradeOptions.value.map(o => String(o.value));
        }
        if (form.merchantType.length === 0 && merchantTypeOptions.value.length) {
          form.merchantType = merchantTypeOptions.value.map(o => String(o.value));
        }
      } else if (!hasMerchant && hadMerchant) {
        // 从"选择商家"变为"未选择商家"时清空
        form.merchantGrade = [];
        form.merchantType = [];

        // 只有在真正取消选择"商家"时才清除校验错误
        nextTick(() => {
          if (formRef.value) {
            formRef.value.clearValidate(["merchantGrade", "merchantType"]);
          }
        });
      }

      // 当用户选择了触达对象时，清除触达对象的验证错误
      if (newTargetsStr && newTargetsStr.split(",").length > 0) {
        nextTick(() => {
          if (formRef.value) {
            formRef.value.clearValidate(["targets"]);
          }
        });
      }
    }
  );

  /** 类目变更联动触达对象选项 */
  watch(
    () => form.categoryId,
    () => handleRefreshTargetsByCategory()
  );

  /* ---------------- wangEditor ---------------- */
  const editorRef = ref();
  const editorHeight = "360px";
  const toolbarCfg = { excludeKeys: [] };
  const { menuConf, uploading, progress } = useWangUpload({
    imgMaxMB: 10,
    fileMaxMB: 20,
    videoMaxMB: 100,
    isSecretFile: false,
  });
  const editorCfg = { placeholder: "请输入内容…", MENU_CONF: menuConf };
  const handleEditorCreated = editor => (editorRef.value = Object.seal(editor));
  onBeforeUnmount(() => editorRef.value?.destroy?.());

  // 处理富文本编辑器内容变化，清除验证错误
  const handleEditorChange = () => {
    // 延迟执行，确保内容已经更新
    nextTick(() => {
      if (formRef.value && hasMeaningfulContent(form.contentHtml)) {
        formRef.value.clearValidate("contentHtml");
      }
    });
  };
  /* ---------------- 其它 ---------------- */
  const MIN_OFFSET_MIN = 5;
  const MS = 60 * 1000;
  const getMinDT = () => new Date(Date.now() + MIN_OFFSET_MIN * MS);

  /** 禁用日期：只允许今天（含）以后的日期 */
  const isDateDisabled = date => {
    const min = getMinDT();
    const d0 = new Date(date);
    d0.setHours(0, 0, 0, 0);
    const m0 = new Date(min);
    m0.setHours(0, 0, 0, 0);
    return d0.getTime() < m0.getTime();
  };

  /** 简单格式化为 YYYY-MM-DD HH:mm:ss */
  const pad = n => (n < 10 ? "0" + n : "" + n);
  const formatDateTime = dt => {
    const y = dt.getFullYear();
    const m = pad(dt.getMonth() + 1);
    const d = pad(dt.getDate());
    const h = pad(dt.getHours());
    const mi = pad(dt.getMinutes());
    const s = pad(dt.getSeconds());
    return `${y}-${m}-${d} ${h}:${mi}:${s}`;
  };

  /** 变更时强制不早于“当前 + 5 分钟” */
  const handleScheduleChange = val => {
    if (!val) return;
    const picked = new Date(val).getTime();
    const min = getMinDT().getTime();
    if (Number.isFinite(picked) && picked < min) {
      $msg?.warning?.(`请选择 ${MIN_OFFSET_MIN} 分钟之后的时间`);
      form.scheduleTime = formatDateTime(new Date(min));
    }
  };

  const handleGotoCategory = () => router.push({ path: "/message/notice/category" });

  /* ---------------- 详情回显 ---------------- */
  const resetForm = () => {
    // 立即清除所有验证错误
    if (formRef.value) {
      formRef.value.clearValidate();
    }

    // 重置表单数据
    formRef.value?.resetFields?.();
    form.categoryId = "";
    form.contentHtml = "";
    form.sendMode = "NOW";
    form.scheduleTime = "";
    form.targets = [];
    form.merchantGrade = [];
    form.merchantType = [];
    form.isScroll = 0;
    form.scrollHours = "";
    form.isPopup = 0;

    // 延迟重置，确保验证错误被完全清除
    setTimeout(() => {
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    }, 50);
  };

  async function loadDetail(detailId) {
    try {
      // 确保下拉/字典已就绪（避免回显时选项还没来）
      if (catOptions.value.length === 0) await loadCategoryTree();
      if (!dictAllTargets.value.length) await loadApplicableDict();
      if (!merchantGradeOptions.value.length || !merchantTypeOptions.value.length) {
        await loadMerchantDicts();
      }

      // ⬇️ 这里按你们真实接口名替换
      const res = await Api.message.GetMsgDetail({ id: detailId });
      const d = res?.data ?? res ?? {};

      // 1) 类目
      form.categoryId = String(d.categoryId ?? d.categoryID ?? "");

      // 2) 标题 & 内容
      form.title = d.title ?? d.messageTitle ?? "";
      form.contentHtml = d.content ?? d.messageContent ?? "";

      // 3) 发送方式/时间
      const rawSendType = String(d.sendType ?? d.sendMethod ?? "").toUpperCase();
      form.sendMode = rawSendType === "TIMING" ? "SCHEDULE" : rawSendType === "MANUAL" ? "MANUAL" : "NOW";
      form.scheduleTime = d.sendTime ?? d.scheduledSendTime ?? "";

      // 4) 触达对象
      const targetStr = d.target ?? d.target ?? "";
      form.targets = String(targetStr)
        .split(",")
        .map(s => s.trim())
        .filter(Boolean);

      // 5) 滚动 & 弹出
      const to01 = v => (String(v) === "1" ? 1 : 0);
      form.isScroll = to01(d.isScroll ?? 0);
      form.scrollHours = String(d.scrollDuration ?? d.scrollHours ?? "");
      form.isPopup = to01(d.isPopup ?? 0);

      // 6) 商家等级/类型
      const splitToArr = v =>
        String(v || "")
          .split(",")
          .map(s => s.trim())
          .filter(Boolean);

      form.merchantGrade = splitToArr(d.merchantLevel);
      form.merchantType = splitToArr(d.merchantType);
    } catch (e) {
      console.error("加载公告详情失败：", e);
      $msg?.error?.("加载详情失败");
    }
  }

  /* ---------------- 提交 ---------------- */
  const handleSubmit = async () => {
    // 定时发送的前置校验（与表单校验解耦，避免来回触发）
    if (form.sendMode === "SCHEDULE") {
      if (!form.scheduleTime) return $msg.warning("请选择定时发送时间");
      if (new Date(form.scheduleTime).getTime() <= Date.now()) {
        return $msg.warning("发送时间需大于当前时间");
      }
    }

    // 表单校验
    const ok = await formRef.value
      .validate()
      .then(() => true)
      .catch(() => false);
    if (!ok) return;

    // 是否包含“商家”对象
    const hasMerchant = form.targets.includes(String(merchantCode.value));

    // 组装提交 payload（对齐你发的接口字段）
    const payload = {
      categoryId: Number(form.categoryId), // ✅ 下拉选中的类目ID
      title: form.title,
      content: form.contentHtml,

      sendType: SEND_MAP_API[form.sendMode], // NOW / MANUAL / TIMING
      sendTime: form.sendMode === "SCHEDULE" ? form.scheduleTime : "",

      isScroll: Number(form.isScroll), // 0/1
      scrollDuration: form.isScroll === 1 ? Number(form.scrollHours) : 0, // 小时

      isPopup: Number(form.isPopup), // 0/1

      targetType: (form.targets || []).join(","), // 适用对象（逗号）
      merchantLevel: hasMerchant ? (form.merchantGrade || []).join(",") : "",
      merchantType: hasMerchant ? (form.merchantType || []).join(",") : "",

      categoryType: "ANNOUNCEMENT", // 你接口里是必传
    };

    try {
      submitting.value = true;

      if (isEdit.value) {
        // 若你们有单独的编辑接口，把下一行替换为 Api.message.EditMsg({...})
        await Api.message.UpdatedMsg({ id: Number(id.value), ...payload });
        $msg.success("保存成功");
      } else {
        await Api.message.AddMsg(payload);
        $msg.success("新增成功");
        // 复用你已有的 resetForm
        resetForm();
      }
    } finally {
      submitting.value = false;
    }
  };

  watch(
    id,
    async newId => {
      if (!newId) {
        resetForm();
        handleRefreshTargetsByCategory();
        return;
      }
      await loadDetail(newId);
    },
    { immediate: true }
  );
  /* ---------------- 初始化 ---------------- */
  onMounted(async () => {
    await Promise.all([loadApplicableDict(), loadCategoryTree(), loadMerchantDicts()]);
    handleRefreshTargetsByCategory();
  });
</script>

<style scoped lang="scss">
  /* footer */
  .footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;

    display: flex;
    align-items: center;
    justify-content: center;

    width: 100%;
    height: 78px;

    background-color: var(--bg);
  }

  /* 表单容器内边距 */
  .content-form {
    padding: 12px 4px;
  }
  /* 表单项标签里的“文字 + 图标” */
  .fi-label {
    display: inline-flex;
    align-items: center;
    gap: 4px; /* 想更贴近可改成 2 或 0 */
    white-space: nowrap; /* 防止换行 */
  }

  .fi-icon {
    cursor: help;
    vertical-align: middle;
  }
  /* 灰底容器，强制同一行显示 */
  .scroll-box {
    display: inline-flex;
    align-items: center;
    gap: 8px; /* 元素间距 */
    padding: 12px 16px;
    border-radius: 6px;

    border: 1px solid var(--cb1);
    // background: var(--el-fill-color-light);
    white-space: nowrap; /* ✅ 关键：中文不换行 */
  }

  /* 标签与单位也不允许换行（双保险） */
  .scroll-label,
  .scroll-unit {
    white-space: nowrap;
  }

  /* 输入框宽度固定，避免被压缩产生换行错觉 */
  .scroll-input {
    width: 180px; /* 你可按视觉改成 160/200 等 */
  }

  /* 商家筛选卡片 */
  .merchant-card {
    box-sizing: border-box;

    padding: 16px;

    border: 1px solid var(--el-border-color);
    border-radius: 8px;

    background: #fff;
  }

  /* 间距工具类 */
  .mb-2 {
    margin-bottom: 8px;
  }

  /* 标签右对齐 */
  :deep(.el-form-item--label-right .el-form-item__label) {
    justify-content: center;
  }
</style>
